package com.cskaoyan.demo5.servlet;

import com.cskaoyan.demo5.common.CommonServlet;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

@WebServlet("/parameter/*")
public class ParameterServlet extends CommonServlet {
    // GET localhost:8080/demo5/parameter/keyAndValue?name=zs&age=18
    // POST localhost:8080/demo5/parameter/keyAndValue 请求体中name=zs&age=18
    @SneakyThrows
    public void keyAndValue(HttpServletRequest request, HttpServletResponse response){
        //Get请求的参数   name=zs&age=18
        String queryString=null;
        if ("GET".equals(request.getMethod())) {
            queryString=request.getQueryString();
        }else {
            queryString=request.getReader().readLine();
        }
        String[] paramterArray = queryString.split("&");
        for (String parameter : paramterArray) {
            String[] keyValue = parameter.split("=");
            String key = keyValue[0];
            String value = keyValue[1];
            System.out.println(key+" : "+value);
        }
    }

    // GET localhost:8080/demo5/parameter/keyAndValue2?name=zs&age=18&hobby=sing&hobby=dance&hobby=rap&hobby=basketball
    // POST localhost:8080/demo5/parameter/keyAndValue2 请求体中name=zs&age=18&hobby=sing&hobby=dance&hobby=rap&hobby=basketball
    public void keyAndValue2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 这个方法帮我们分析了key=value&key=value形式的请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        //获取参数名称
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            System.out.println(parameterName);
        }
        //根据请求参数的名称直接从数组中取出第一个值
        String value = request.getParameter("hobby");
        System.out.println(value);
        //key相同时、可以获取所有值
        String[] values = request.getParameterValues("hobby");
        System.out.println(Arrays.toString(values));
    }

    /**
     * 解决POST请求中的中文乱码问题
     * @param request
     * @param response
     */
    public void characterUTF8(HttpServletRequest request,HttpServletResponse response) throws IOException {
        // 解决问题 → 使用request之前先设置字符集
        request.setCharacterEncoding("UTF-8"); // 这个你也可以写在CommonServlet中的doGet或doPost方法中
        // 复现问题
        String jsonStr = request.getReader().readLine();
        System.out.println(jsonStr);
    }

}
